package com.laoma.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object>  {
    @Override
    public GatewayFilter apply(Object config) {
        return new AuthGatewayFilter();
    }
      //因为配置中没有等号后面的具体值，所以这里也不用定义Config和值对应关系了，
//    @Override
//    public List<String> shortcutFieldOrder() {
//        return null;
//    }

    //具体实现的filter。其实可以单独把这个内部类单独出一个类。
    class AuthGatewayFilter implements GatewayFilter, Ordered {
        @Override
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            //获取header中的Authorization,可能是jwt生成的token，包含用户名等信息
            String authorization = exchange.getRequest().getHeaders().getFirst("Authorization");
            //权限比较。可以使redis中缓存的登陆信息，也可能是调用第三方认证的接口。
            boolean permitted = "123456".equals(authorization);
            if (permitted) {
                return chain.filter(exchange);
            }
            else {
                //如果没有校验通过，返回401
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
        }
        @Override
        public int getOrder() {
            return 10;
        }
    }
}
